package com.wuxiaoqin.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wuxiaoqin.server.entity.*;
import com.wuxiaoqin.server.entity.order.OrdCreaParm;
import com.wuxiaoqin.server.entity.order.OrderList;
import com.wuxiaoqin.server.mapper.*;
import com.wuxiaoqin.server.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuxiaoqin.server.service.IShoppingsService;
import com.wuxiaoqin.server.service.IUsersService;
import com.wuxiaoqin.uitls.respObj.RespBean;
import com.wuxiaoqin.uitls.util.DateUtil;
import com.wuxiaoqin.uitls.util.OrderNumUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2021-11-05
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    @Autowired
    private IUsersService usersService;
    @Autowired
    private IShoppingsService shoppingsService;

    @Autowired
    private OrdergoodMapper ordergoodMapper;
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private ShoppingsMapper shoppingsMapper;
    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private GoodsstockMapper goodsstockMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private IUsersService iUsersService;

    //生成订单(需要研究一下)
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public RespBean creatOrder(OrdCreaParm ordCreaParm) throws Exception {

        //创建订单对象
        OrderList orderList = new OrderList();
        //当前登录用户
        Users currentUser = usersService.getCurrentUser();
        Integer uId = currentUser.getUId();

        //订单号
        Integer orderNumber = OrderNumUtil.getOrderNumber();

        //当前时间
        String createTime = DateUtil.ptfDate();
        //付款金额
        BigDecimal payment=new BigDecimal(0);

        Integer integral = ordCreaParm.getIntegral();
        Integer uPoints = usersService.getCurrentUser().getUPoints();
        if (integral >uPoints){
            return RespBean.error("积分不足");
        }
        //获取勾选的购物车列表
        List<Shoppings> shoppings = shoppingsMapper.selectList(
                new QueryWrapper<Shoppings>()
                        .eq("U_id", uId).eq("S_state", 1)
        );
        String img="";
        try {
            for (Shoppings cart : shoppings) {

                Integer sNum = cart.getSNum();
                Integer cId = cart.getCId();
                String sSize = cart.getSSize();
                //获取库存，销售量
                Commodity commodity = commodityMapper.selectOne(
                        new QueryWrapper<Commodity>().eq("C_id", cId)
                );
                //存入第一张图片
                if ("".equals(img) ){
                    img = commodity.getCImg();
                }
                Integer stockNum = stockNum(sSize, cId);//获取库存
                if (stockNum<=sNum){//如果商品数量不足返回空
                    return RespBean.error("商品数量不足");
                }
                //乐观锁防止高并发超卖,超卖则返回0并抛出异常，正常售出返回1
                UpdateWrapper<Goodsstock> stockUpdateWrapper = new UpdateWrapper<>();
                stockUpdateWrapper.eq("C_id", cId).set(sSize,stockNum-sNum);
                int i = goodsstockMapper.update(null, stockUpdateWrapper);


                commodity.setCSalesvolumes(commodity.getCSalesvolumes()+sNum);
                commodityMapper.updateById(commodity);
                if (i==0){
                    throw new Exception();
                }
            }

                //得到选中购物车的商品的价格
                for (Shoppings shopping : shoppings) {
                    Commodity cprice = commodityMapper.selectOne(new QueryWrapper<Commodity>().eq("C_id", shopping.getCId()));
                    payment = cprice.getCPrice().multiply(new BigDecimal(shopping.getSNum())).add(payment);
                }
                BigDecimal actualPayment = payment.subtract(new BigDecimal(integral));

                //填充订单
                orderList.setOrderno(orderNumber);
                orderList.setPayment(actualPayment);
                orderList.setStatus(10);//表示未支付的状态，支付完后要改值
                orderList.setStatusdesc("未支付");
                orderList.setCreatetime(createTime);
                orderList.setUId(uId);
                orderList.setAddId(ordCreaParm.getAddressid());
                orderList.setAddress(getAdd(ordCreaParm.getAddressid()));//地址信息
                orderList.setImgage(img);
                orderList.setIntegral(integral);
                orderList.setOrgprice(payment);
                //
                class OrderCancel implements Runnable {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1800000);//回滚时间半小时1800000
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        int orderStatus = getOrderStatus(orderNumber);
                        if (orderStatus == 0) {
                            System.out.println("=========================");
                            delOrder(orderNumber);
                        }
                    }
                }
                Thread thread = new Thread(new OrderCancel(), "取消订单监听线程");
                thread.start();

                //插入订单
                Orders orders = new Orders(orderNumber,uId,0,0,"未支付","",createTime,payment,integral,actualPayment,
                        getAdd(ordCreaParm.getAddressid()).getAddId(), getAdd(ordCreaParm.getAddressid()).getAddName()
                        ,getAdd(ordCreaParm.getAddressid()).getAddPhone()
                        ,getAdd(ordCreaParm.getAddressid()).getAddAddress(),img);
                int insert = ordersMapper.insert(orders);
                if(insert ==0){
                   return RespBean.error("订单生成失败");
                }

                //扣除用户积分
                Users currentUser1 = usersService.getCurrentUser();
                currentUser1.setUPoints(currentUser1.getUPoints() - integral);
                usersMapper.updateById(currentUser1);

                //插入ordergood
                for (Shoppings shopping : shoppings) {
                    Commodity commodity = commodityMapper.selectOne(new QueryWrapper<Commodity>().eq("C_id", shopping.getCId()));
                    Ordergood ordergood = new Ordergood(orderNumber,shopping.getCId(),commodity.getCName(),
                            shopping.getSSize(),commodity.getCPrice(),shopping.getSNum()
                            ,commodity.getCPrice().multiply(new BigDecimal(shopping.getSNum()))
                            ,0,commodity.getCImg());
                    ordergoodMapper.insert(ordergood);
                }
                //删除购物车
            int delete = shoppingsMapper.delete(new QueryWrapper<Shoppings>()
                    .eq("U_id", uId).eq("S_state", 1));
                if (delete == 0){
                    return RespBean.error("用户删除购物车报错");
                }
            List<Ordergood> ordergoodList = ordergoodMapper.selectList(new QueryWrapper<Ordergood>().eq("orderNo", orderNumber));
            orderList.setOrderItemList(ordergoodList);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();;
        }
        return RespBean.success("成功",orderList);
    }

    /**
     * 获取订单状态
     * @param orderid
     * @return
     */
    @Override
    public int getOrderStatus(Integer orderid) {
        System.out.println("statue");
        return ordersMapper.selectById(orderid).getStatus();
    }



    /**
     * 获取用户地址
     * @param addId
     * @return
     */
    @Override
    public Address getAdd(Integer addId) {
        Address address = addressMapper.selectById(addId);
        return address;
    }

    /**
     * 取消订单
     * @param orderid
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public void delOrder(int orderid) {

        try {
            Orders orders = ordersMapper.selectById(orderid);
//            //回滚积分
            Integer integral = orders.getIntegral();
            Users user = usersMapper.selectById(orders.getUId());
            user.setUPoints(user.getUPoints()+integral);
            usersMapper.updateById(user);

            ordersMapper.deleteById(orderid);


            //删除订单项
            List<Ordergood> ordItems = ordergoodMapper.selectList(
                    new QueryWrapper<Ordergood>().eq("orderNo", orderid));
            for (Ordergood ordItem : ordItems) {

                //商品id
                Integer cId = ordItem.getCId();

                //订单的商品数量
                Integer orderSum = ordItem.getGoodssum();
                String cSize = ordItem.getCSize();

                //回滚销售量
                Commodity c_id = commodityMapper.selectOne(new QueryWrapper<Commodity>().eq("C_id", cId));
                c_id.setCSalesvolumes(c_id.getCSalesvolumes()-orderSum);
                commodityMapper.updateById(c_id);


                //回滚库存
                Integer stockNum = stockNum(cSize, cId);
                UpdateWrapper<Goodsstock> stockUpdateWrapper = new UpdateWrapper<>();
                stockUpdateWrapper.eq("C_id", cId).set(cSize,stockNum + orderSum);
                int i = goodsstockMapper.update(null, stockUpdateWrapper);
                //goodsstockMapper.updateById(goodsstock);
            }
            //删除订单
            ordergoodMapper.delete(new QueryWrapper<Ordergood>().eq("orderNo", orderid));
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    /**
     * 通过用户id获取订单列表
     * @param uId
     * @return
     */
    @Override
    public RespBean getOrderByUserId(Integer uId) {
        List<Orders> ordersList = ordersMapper.selectList(new QueryWrapper<Orders>().eq("U_id", uId));
        return RespBean.success("成功",ordersList);
    }

    /**
     * 通过id获取订单
     * @param uId
     * @param orderid
     * @return
     */
    @Override
    public RespBean getOrderById(Integer uId, Integer orderid) {
        Orders orders = ordersMapper.selectOne(new QueryWrapper<Orders>().eq("U_id", uId).eq("orderNo", orderid));
        if (orders == null){
            return RespBean.error("该订单不存在");
        }
        return RespBean.success("成功",orders);
    }

    /**
     * 订单商品
     * @param uId
     * @param orderid
     * @return
     */
    @Override
    public RespBean getOrderGoods(Integer uId, Integer orderid) {
        Orders orders = ordersMapper.selectOne(new QueryWrapper<Orders>().eq("U_id", uId).eq("orderNo", orderid));
        if (orders == null){
            return RespBean.error("该订单不存在");
        }
        List<Ordergood> ordergoods = ordergoodMapper.selectList(new QueryWrapper<Ordergood>().eq("orderNo", orderid));
        if (ordergoods == null){
            return RespBean.error("该订单不存在");
        }
        return RespBean.success("成功",ordergoods);
    }

    /**
     * 已发货的商品列表
     * @param uId
     * @return
     */
    @Override
    public List<Orders> getOrderFaHuo(Integer uId) {
        List<Orders> orders = ordersMapper.selectList(new QueryWrapper<Orders>().eq("U_id", uId).eq("status", 2));
        return orders;
    }

    /**
     * 确认收货
     * @param uId
     * @param orderNo
     * @return
     */
    @Override
    public RespBean verifyShouHuo(Integer uId, Integer orderNo) {

        Orders orders = ordersMapper.selectOne(new UpdateWrapper<Orders>()
                .eq("U_id", uId).eq("orderNo", orderNo));
        if (orders==null){
            return RespBean.error("操作有误");
        }
        int update = ordersMapper.update(null, new UpdateWrapper<Orders>()
                .eq("U_id", uId).eq("orderNo", orderNo)
                .set("status", 3)
                .set("statusDesc", "已收货")
        );
        if (update<=0){
            return RespBean.error("确认收货不成功！");
        }

        return RespBean.success("确认收货成功！");
    }

    //获取库存数量
    public Integer stockNum(String cSize,Integer cId){
        QueryWrapper<Goodsstock> queryWrapper = new QueryWrapper<Goodsstock>().select(cSize).eq("C_id", cId);
        List<Object> cidList = goodsstockMapper.selectObjs(queryWrapper);
        return (Integer)cidList.get(0);//库存
    }


}
